/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
 package com.wealth.vote.web.controller;

import iaas.enums.StatusEnum;
import iaas.utils.RedirectMessage;
import iaas.web.JqGridRequest;
import iaas.web.JqGridResponse;
import iaas.web.JqGridUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wealth.vote.entity.Cooperative;
import com.wealth.vote.entity.CooperativeArea;
import com.wealth.vote.service.ICooperativeAreaService;
import com.wealth.vote.service.ICooperativeService;
import com.wealth.vote.service.VoteService;
import com.google.common.collect.Lists;
import com.wealth.system.entity.User;
import com.wealth.system.service.ShiroUser;
import com.wealth.system.web.controller.BaseController;

/**
 * @author chan
 * @version 1.0
 * @since 1.0
 */
 
@Controller
@RequestMapping(value="/manage/vote/cooperative")
public class CooperativeController extends BaseController{

	Logger logger = Logger.getLogger(CooperativeController.class);
	
	@Autowired
	private ICooperativeService cooperativeService;
	@Autowired
	private ICooperativeAreaService areaService;
	@Autowired
	private VoteService voteService;
	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Classify对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void init(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) {
		try{
			if (id != -1) {
				Cooperative cooperative = cooperativeService.get(id);
				model.addAttribute("cooperative", cooperative);
			}
		}catch(Exception e){
			logger.error("初始化错误", e);
		}
	}
	
	/**
	 * 列表
	 */
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String list(Model model){
		try {
			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			model.addAttribute("corpid", corpid);
			List<CooperativeArea> areaList= areaService.getAllArea();
			model.addAttribute("areaList", areaList);
			return "vote/cooperative/list";
			
		} catch (Exception e) {
			logger.error(e);
			return "system/500";
		}
	}
	
	
	/**
	 * 列表ajax查询数据
	 */
	@RequestMapping(value="/list",method = RequestMethod.POST)
	@ResponseBody
	public JqGridResponse getJson(Model model,JqGridRequest request) {
		try{

			Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
			
			Page<Cooperative> page = cooperativeService.get(corpid, request,Cooperative.class);
			
			return JqGridUtil.getJqGrirdResponse(page);
		}catch(Exception e){
			logger.error("列表错误！", e);
			return null;
		}
	}
	
	
	/**
	 * 详情
	 */
	@RequestMapping(value="/{id}",method = RequestMethod.GET)
	public String infoForm(Model model,@PathVariable("id") Long id){
		try{
			Cooperative cooperative = cooperativeService.get(id);
			model.addAttribute("cooperative", cooperative);
			return "vote/cooperative/info";
		}catch(Exception e){
			logger.error("详情页面错误,id="+id, e);
			return "system/500";
		}
	}
	
	
	/**
	 * 创建页面
	 */
	@RequestMapping(value="/create",method = RequestMethod.GET)
	public String createForm(){
		try {
			return "vote/cooperative/create";
		} catch (Exception e) {
			logger.error("创建页面错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 创建
	 */
	@RequestMapping(value="/create",method = RequestMethod.POST)
	public String create(Model model,Cooperative entity,RedirectAttributes redirectAttributes){
		try {
			User user = ShiroUser.getInstance().getUser();
			
			entity.setCreateTime(new Date());
			entity.setStatus(StatusEnum.NORMAL.getValue());
			cooperativeService.save(entity);
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("创建成功"));
			return "redirect:/manage/vote/cooperative/list";
		} catch (Exception e) {
			logger.error("创建错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 编辑页面
	 */
	@RequestMapping(value="/update/{id}",method = RequestMethod.GET)
	public String setUpdateForm(Model model,@PathVariable("id") Long id){
		try{
			Cooperative cooperative = cooperativeService.get(id);
			model.addAttribute("cooperative", cooperative);
			return "vote/cooperative/update";
		}catch(Exception e){
			logger.error("编辑页面错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 修改信息
	 */
	@RequestMapping(value="/update/{id}",method = RequestMethod.POST)
	public String update(@PathVariable("id") Long id,@ModelAttribute("cooperative") Cooperative cooperative,RedirectAttributes redirectAttributes){
		try{
			cooperativeService.save(cooperative);
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("编辑成功"));
			return "redirect:/manage/vote/cooperative/list";
		}catch(Exception e){
			logger.error("编辑错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 删除（逻辑删除）
	 */
	@RequestMapping(value="/delete/{id}",method = RequestMethod.GET)
	public String delete(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			cooperativeService.deleteLogical(id);
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("删除成功"));
			return "redirect:/manage/vote/cooperative/list";
		}catch(Exception e){
			logger.error("删除错误,id="+id,e);
			return "system/500";
		}
	}
	
	/**
	 * 停用
	 */
	@RequestMapping(value="/disable/{id}",method = RequestMethod.GET)
	public String disable(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			cooperativeService.updateStatus(id, StatusEnum.STOP.getValue());
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipWarning("停用成功"));
			return "redirect:/manage/vote/cooperative/list";
		}catch(Exception e){
			logger.error("停用错误,id="+id,e);
			return "system/500";
		}
	}
	
	/**
	 * 启用
	 */
	@RequestMapping(value="/enable/{id}",method = RequestMethod.GET)
	public String enable(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			cooperativeService.updateStatus(id, StatusEnum.NORMAL.getValue());
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipWarning("启用成功"));
			return "redirect:/manage/vote/cooperative/list";
		}catch(Exception e){
			logger.error("启用错误,id="+id,e);
			return "system/500";
		}
	}
	
	
	/**导入数据*/
	@RequestMapping(value="/intoData/{id}")
	public String intoArea(@PathVariable Long id,DefaultMultipartHttpServletRequest request, RedirectAttributes redirectAttributes){
		try {
			MultipartFile file = request.getFile("file");
			Workbook workbook = WorkbookFactory.create(file.getInputStream());		
			//工作表
			Sheet sheet =workbook.getSheetAt(0); 					
			//总行
			int rows = sheet.getLastRowNum();																
			//遍历行, r=0 对应说明文字
			List<Cooperative> cooperList = Lists.newArrayList(); 
			for (int r = 1; r<=rows; r++) {
				Row row  = sheet.getRow(r);
				if(row==null){
					continue;
				}
				//总列
				int cells = row.getLastCellNum();			
				//商品
				Cooperative cooper = new Cooperative();
				//遍历每一列
				for (int col = 0; col<cells; col++) {
					//设置每一列为字符串
					if(row.getCell(col)!=null){
						row.getCell(col).setCellType(Cell.CELL_TYPE_STRING);
					}
				}
				Map<String, String> map  = new HashMap<String, String>();
				String key =row.getCell(0)==null?"":row.getCell(0).toString();
				map.put(key, key);
				if(r!=1){
					if(map.containsKey(row.getCell(0)==null?"":row.getCell(0).toString())){
						continue;
					}
				}
				cooper.setArea(new CooperativeArea(id));
				String imgurl = voteService.getVoteImgUrl();
				cooper.setName(row.getCell(0)==null?"":row.getCell(0).toString());
				String s_url=row.getCell(1)==null?"":row.getCell(1).toString();
				String picurl  = imgurl+"/"+s_url;
				cooper.setPicurl(picurl);
				cooper.setCreateTime(new Date());
				cooper.setStatus(StatusEnum.NORMAL.getValue());
				cooperList.add(cooper);
			}   
			cooperativeService.save(cooperList);
			workbook.close();
			return "redirect:/manage/vote/cooperative/list";
		} catch (Exception e) {
			logger.error(e);
			return "system/500";
		}
		
	}
}